/* eslint-disable no-param-reassign */
import React, { Fragment } from 'react';

import {
  CloseCircleOutlined,
  DownOutlined,
  EllipsisOutlined,
  ExclamationCircleOutlined,
  UpOutlined,
  QuestionCircleOutlined,
} from '@ant-design/icons';

import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';

import {
  Card,
  Row,
  Col,
  Select,
  Input,
  Button,
  Badge,
  Alert,
  Modal,
  DatePicker,
  Tabs,
  Menu,
  Dropdown,
  Divider,
  message,
  Tooltip,
  Spin,
} from 'antd';
import queryString from 'query-string';
import moment from 'moment';
import router from 'umi/router';
import { connect } from 'dva';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { checkPermissions } from '@/utils/authority';
import downloadFile, { formatNumber } from '@/utils/utils';
import Authorized from '@/utils/Authorized';
import styles from '@/utils/utils.less';
import StandardTable from '@/components/StandardTable';
import HOCSelect from '@/components/AntDesign/Select';
import NotEnterBillData from './BeforeBill';
import TaskProgress from '../../components/TaskProgress';
import Supplier from '../../components/NsSupplier';
import TextOverFlow from '../../components/TextOverFlow';

const { Option } = Select;
const FormItem = Form.Item;
const { MonthPicker } = DatePicker;
const { confirm } = Modal;
const { TabPane } = Tabs;
let uploadFiles = null;

@connect(({ chargebillns, loading }) => ({
  chargebillns,
  activeKey: chargebillns.activeKey,
  expandForm: chargebillns.expandForm,
  formFieldsValue: chargebillns.formFieldsValue,
  pageData: chargebillns.pageData,
  loading:
    loading.models.chargebillns &&
    !loading.effects['chargebillns/getProgress'] &&
    !loading.effects['chargebillns/uploadFileWithProgress'] &&
    !loading.effects['chargebillns/createBill'] && // 生成账单接口
    !loading.effects['chargebillns/isTask'], // 查看当前有是否在未进账单
  submitLoading:
    loading.effects['chargebillns/isTask'] ||
    loading.effects['chargebillns/uploadFileWithProgress'], // 生成账单的loading
  valuesArr: chargebillns.valuesArr,
}))
class BasicList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      NSBILL_CHRG_STATE: [],
      statusMap: ['', 'default', 'processing', 'warning', 'success'],
      supplyNameListAll: [], // 添加全部
      selectedRowKeys: [],
      selectedRows: [],
      sumPrice: 0,
      exportLoding: false,
    };
  }

  componentDidMount() {
    this.checkHasTask();
    const { dispatch } = this.props;
    // 获取字典
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: ['NSBILL_CHRG_STATE'],
    }).then(data => {
      if (data && data.NSBILL_CHRG_STATE && data.NSBILL_CHRG_STATE.length) {
        this.setState({ NSBILL_CHRG_STATE: data.NSBILL_CHRG_STATE });
      }
    });
    // 签约方列表
    dispatch({
      type: 'chargebillns/getSuppIdList',
      payload: {
        name: null,
      },
    }).then(res => {
      if (res.success) {
        const all = { suppId: 'SUPP_ALL', name: '全部' };
        this.setState({
          supplyNameListAll: [all, ...res.data],
        });
      } else {
        message.warning(`${res.message || '暂无数据！'}`);
      }
    });
    this.getInitialList();
  }

  componentWillUnmount() {
    window.clearInterval(uploadFiles);
  }

  // 查看当前有无任务
  checkHasTask = () => {
    const { dispatch } = this.props;
    // 查看当前有无任务进行
    dispatch({
      type: 'chargebillns/checkCreateBillTask',
    });
  };

  // 进度弹框显隐
  handleProgressModalVisible = flag => {
    const {
      activeKey,
      pageData: { pagination },
      dispatch,
      formFieldsValue,
    } = this.props;
    if (!flag) {
      dispatch({
        type: 'chargebillns/updateModelData',
        payload: {
          showProgress: false,
        },
      });
      this.searchList(
        this.processFormData(formFieldsValue),
        activeKey,
        pagination.current,
        pagination.pageSize
      );
    }
  };

  // 查询表格布局
  toggleForm = () => {
    const { expandForm, dispatch } = this.props;
    dispatch({
      type: 'chargebillns/updateModelData',
      payload: {
        expandForm: !expandForm,
      },
    });
  };

  getInitialList = () => {
    const {
      pageData: { pagination },
      dispatch,
      location,
      formFieldsValue,
      form,
      activeKey,
    } = this.props;
    const tempActiveKey = queryString.parse(location.search).activeKey || activeKey;
    if (location.queryParam) {
      if (location.queryParam && location.queryParam.suppId) {
        location.queryParam.sendSuppId = location.queryParam.suppId;
      }
      if (location.queryParam && location.queryParam.name) {
        dispatch({
          type: 'publicdata/getCustList',
          payload: [{ sendSuppId: location.queryParam.sendSuppId, name: location.queryParam.name }],
        });
        form.setFieldsValue({ sendSuppId: location.queryParam.sendSuppId });
      }
      dispatch({
        type: 'chargebillns/updateModelData',
        payload: { formFieldsValue: location.queryParam, expandForm: true },
      });
    }
    dispatch({
      type: 'chargebillns/updateModelData',
      payload: {
        activeKey: tempActiveKey,
        progressPercent: 0,
      },
    });
    this.searchList(
      this.processFormData({ ...formFieldsValue }),
      tempActiveKey,
      pagination.current,
      pagination.pageSize
    );
  };

  // 点击查询按钮
  searchBtnList = activeKey => {
    const { form, valuesArr, dispatch } = this.props;
    form.validateFieldsAndScroll([...valuesArr], (err, values) => {
      if (!err) {
        dispatch({
          type: 'chargebillns/updateModelData',
          payload: {
            formFieldsValue: values,
            activeKey,
          },
        });
        this.searchList(this.processFormData(values), activeKey);
      }
    });
  };

  // 查询
  searchList = (
    formFieldsValue,
    activeKey = '1',
    currentPage = 1,
    pageSize = 10,
    isClear = true
  ) => {
    if (isClear) {
      this.setState({
        selectedRowKeys: [],
        selectedRows: [],
        sumPrice: 0,
      });
    }
    const { dispatch } = this.props;
    const pageArg = {
      currentPage,
      pageSize,
    };
    const params = {
      ...formFieldsValue,
      pageArg,
    };

    dispatch({
      type: 'chargebillns/updateModelData',
      payload: {
        params,
      },
    });

    if (activeKey === '2') {
      dispatch({
        type: 'chargebillns/getNotEnterList',
        payload: params,
      });
    } else {
      dispatch({
        type: 'chargebillns/getList',
        payload: params,
      });
    }
  };

  // 处理form数据
  processFormData = fieldsValue => {
    const formFieldsValue = {};
    const tempFieldsValue = fieldsValue;
    Object.entries(tempFieldsValue).forEach(([key, value]) => {
      if (!value) {
        formFieldsValue[key] = null;
      } else if (key === 'billYm') {
        formFieldsValue[key] = value.format('YYYYMM');
      } else if (value.key) {
        formFieldsValue[key] = value.key;
      } else {
        formFieldsValue[key] = value;
      }
    });
    return formFieldsValue;
  };

  // 重置查询
  resetSearch = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    form.setFieldsValue({ billYm: null });
    this.state.selectedRowKeys = [];
    this.state.selectedRows = [];
    dispatch({
      type: 'chargebillns/updateModelData',
      payload: {
        formFieldsValue: {},
      },
    });
  };

  // 切换页签
  changeTabPane = activeKey => {
    const {
      pageData: { pagination },
      dispatch,
      formFieldsValue,
    } = this.props;
    router.push(`/chargmanage/chargebillns/index?activeKey=${activeKey}`);
    dispatch({
      type: 'chargebillns/updateModelData',
      payload: {
        activeKey,
        formFieldsValue: {
          ...formFieldsValue,
        },
      },
    });
    if (Number(activeKey) === 1) {
      this.searchList(
        this.processFormData(formFieldsValue),
        activeKey,
        pagination.current,
        pagination.pageSize
      );
    }
  };

  // 切换模态框：新增、修改
  handleModalVisible = flag => {
    const { dispatch } = this.props;
    dispatch({
      type: 'chargebillns/updateModelData',
      payload: { modalVisible: !!flag },
    });
  };

  // 提交生成账单数据
  submitData = () => {
    const { dispatch, form } = this.props;
    let submitData = {};
    form.validateFieldsAndScroll(['suppIdModal', 'billYmModal'], (err, values) => {
      if (!err) {
        // eslint-disable-next-line no-restricted-syntax
        for (const key in values) {
          if (values[key] && values[key].key) {
            values[key] = values[key].key;
          } else if (key === 'billYmModal') {
            values[key] = values[key].format('YYYYMM');
          } else {
            values[key] = values[key] ? values[key] : '';
          }
        }
        submitData = { sendSuppId: values.suppIdModal, billYm: values.billYmModal };
        // 是否在未进账单生成
        dispatch({
          type: 'chargebillns/isTask',
          payload: submitData,
        }).then(response => {
          // eslint-disable-next-line eqeqeq
          if (response.success && response.data == 0) {
            dispatch({
              type: 'chargebillns/uploadFileWithProgress',
              payload: { batchType: 1, params: submitData },
            });
          } else {
            message.warning('当前客户已生成过选择月份账单，增量数据请到未进账单页面生成!');
          }
        });
      }
    });
  };

  // 问题人员导出数据
  export = singleOrMerge => {
    const { selectedRowKeys } = this.state;
    if (!selectedRowKeys.length) {
      message.warning('请至少选择一条账单数据');
    } else {
      this.exportExcel(singleOrMerge);
    }
  };

  // 导出excel
  exportExcel = singleOrMerge => {
    const { selectedRowKeys } = this.state;
    const params = {
      billIdList: selectedRowKeys,
    };
    const { dispatch } = this.props;
    this.setState({
      exportLoding: true,
    });
    dispatch({
      type:
        singleOrMerge === 'downSingleBillDet'
          ? 'chargebillns/singleExport'
          : 'chargebillns/mergeExport',
      payload: params,
    }).then(res => {
      if (res.success) {
        uploadFiles = setInterval(() => {
          dispatch({
            type: 'chargebillns/uploadFile',
            payload: { billKey: res.data, downType: singleOrMerge === 'downSingleBillDet' ? 2 : 3 },
          }).then(resFile => {
            if (resFile.success) {
              if (resFile.success && resFile.data && resFile.data.fileId && resFile.data.fileName) {
                window.clearInterval(uploadFiles);
                downloadFile(
                  { fileId: resFile.data.fileId, fileName: resFile.data.fileName },
                  '/csApi/fileServer/downloadFile',
                  'GET',
                  () => {
                    this.setState({
                      exportLoding: false,
                    });
                  }
                );
              }
            } else {
              message.warning(resFile.message || '下载失败');
              window.clearInterval(uploadFiles);
              this.setState({
                exportLoding: false,
              });
            }
          });
        }, 2000);
      } else {
        this.setState({
          exportLoding: false,
        });
        window.clearInterval(uploadFiles);
        message.warning(res.message || '下载失败');
      }
    });
  };

  // 合并账单
  mergeBill = () => {
    const { selectedRowKeys } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: 'chargebillns/checkCreateBillTask',
      // eslint-disable-next-line consistent-return
    }).then(response => {
      if (response.success) {
        if (response.data && response.data.taskCode === 3) {
          message.warning('当前有账单任务正在生成，请稍后操作！');
          return false;
          // eslint-disable-next-line no-else-return
        } else {
          // eslint-disable-next-line no-lonely-if
          if (selectedRowKeys.length >= 2) {
            if (this.validateState()) {
              message.warning('只有待发签约方和签约方拒绝的可以合并');
              return false;
            }
            confirm({
              icon: <QuestionCircleOutlined />,
              title: '你确定要合并吗?',
              okText: '合并',
              okType: 'default',
              cancelText: '取消',
              style: { top: 200 },
              onOk: () => {
                dispatch({
                  type: 'chargebillns/uploadFileWithProgress',
                  payload: { batchType: 2, params: { billIdList: selectedRowKeys } },
                });

                // dispatch({
                //   type: 'chargebillns/mergeBill',
                //   payload: { billIdList: selectedRowKeys },
                // }).then(res => {
                //   if (res.success) {
                //     dispatch({
                //       type: 'chargebillns/updateModelData',
                //       payload: {
                //         billTaskId: res.data.billTaskId,
                //       },
                //     });
                //     this.viewTaskProgress(true);
                //   } else {
                //     message.warning(`${res.message || '合并失败！'}`);
                //   }
                // });
              },
              onCancel: () => {
                this.setState({ selectedRowKeys: [], sumPrice: 0 });
              },
            });
          } else {
            message.warning('请至少选择两条账单数据');
          }
        }
      } else {
        message.warning(response.message || '服务端未知错误');
      }
    });
  };

  // 标记已收费
  markCharge = () => {
    const {
      dispatch,
      activeKey,
      pageData: { pagination },
      formFieldsValue,
    } = this.props;
    const { selectedRowKeys, selectedRows } = this.state;
    if (selectedRowKeys.length === 0) {
      message.warning('请选择标记已收费的数据');
      return;
    }
    let stateFlag;
    const billNoList = [];
    selectedRows.forEach(item => {
      if (+item.billState !== 4) {
        stateFlag = true;
        billNoList.push(item.billNo);
      }
    });
    if (stateFlag) {
      message.warning(
        `账单编号${billNoList.length > 1 ? '分别' : ''}为“${billNoList.join(
          '、'
        )}”的账单不允许标记已收费，只能针对状态为“待收费”的账单操作标记已收费!`
      );
      return;
    }
    Modal.confirm({
      icon: <ExclamationCircleOutlined />,
      title: `已选择${selectedRowKeys.length}条数据，是否确认全部标记已收费`,
      content: '请线下和财务核实每笔账单款项已到账，标记后不可取消标记',
      cancelText: '取消',
      okText: '确认',
      onOk: () => {
        dispatch({
          type: 'chargebillns/markCharge',
          payload: {
            billIdList: selectedRowKeys,
          },
        }).then(res => {
          if (res.success) {
            if (res.data) {
              if (res.data.taskCount === res.data.successCount) {
                message.success('标记成功');
                this.searchList(
                  this.processFormData(formFieldsValue),
                  activeKey,
                  pagination.current,
                  pagination.pageSize
                );
              } else if (res.data.taskCount === res.data.errorCount) {
                Modal.error({
                  icon: <CloseCircleOutlined />,
                  title: '标记失败',
                  content: '所选数据非待收费状态，不可标记已收费',
                  okText: '关闭',
                  okType: 'default',
                  autoFocusButton: 'cancel',
                  onOk: () => {
                    this.searchList(
                      this.processFormData(formFieldsValue),
                      activeKey,
                      pagination.current,
                      pagination.pageSize
                    );
                  },
                });
              } else {
                Modal.warning({
                  icon: <ExclamationCircleOutlined />,
                  title: `标记成功`,
                  content: `已选${res.data.taskCount}条数据中，${
                    res.data.successCount
                  }条已标记成功，${res.data.errorCount}条数据状态非待收费，不可标记`,
                  okText: '关闭',
                  okType: 'default',
                  autoFocusButton: 'cancel',
                  onOk: () => {
                    this.searchList(
                      this.processFormData(formFieldsValue),
                      activeKey,
                      pagination.current,
                      pagination.pageSize
                    );
                  },
                });
              }
            }
          } else {
            message.warning(res.message);
          }
        });
      },
    });
  };

  // 删除账单
  deleteBill = () => {
    const {
      dispatch,
      pageData: {
        pagination: { current, pageSize, total },
      },
      formFieldsValue,
    } = this.props;
    const { selectedRowKeys, selectedRows, NSBILL_CHRG_STATE } = this.state;
    if (selectedRowKeys.length) {
      const iaDisable = selectedRows.some(row => row.billState !== 1);
      if (iaDisable) {
        const idList = [];
        const filterRows = selectedRows.filter(item => item.billState !== 1);
        filterRows.forEach(r => {
          NSBILL_CHRG_STATE.forEach(c => {
            if (c.itemCode === `${r.billState}`) {
              idList.push(r.billNo);
            }
          });
        });
        return message.warning(
          `账单编号${idList.length > 1 ? '分别' : ''}为“${idList.join(
            '、'
          )}”的账单不允许删除，只能针对状态为“待发签约方”的账单操作删除!`
        );
      }
      const billNoList = [];
      selectedRows.forEach(item => {
        billNoList.push(item.billNo);
      });
      confirm({
        icon: <QuestionCircleOutlined />,
        title: `你确定要删除编号为“${billNoList.join('、')}”的账单吗?`,
        content: (
          <div>
            <span>注意：</span>
            <span>
              当月账单全部删除后，需要重新操作生成账单；
              <br />
              <span style={{ opacity: 0 }}>注意：</span>
              当月账单部分删除后，被删除的数据会进入到【未进账单数据】中。
            </span>
          </div>
        ),
        okText: '删除',
        cancelText: '取消',
        width: 570,
        style: { top: 200 },
        onOk: () => {
          dispatch({
            type: 'chargebillns/deleteBill',
            payload: { billIdList: selectedRowKeys },
          }).then(res => {
            if (res.success) {
              const selectedLen = 1;
              if (current > 1 && (total % pageSize === selectedLen || pageSize === selectedLen)) {
                this.searchList(this.processFormData(formFieldsValue), '1', current - 1, pageSize);
              } else {
                this.searchList(this.processFormData(formFieldsValue), '1', current, pageSize);
              }
              this.setState({ selectedRowKeys: [], selectedRows: [] });
              message.success('删除成功！');
            } else {
              message.warning(`${res.message || '删除失败'}`);
            }
          });
        },
        onCancel: () => {
          this.setState({ selectedRowKeys: [], sumPrice: 0 });
        },
      });
    } else {
      message.warning('请至少选择一条账单数据');
    }
    return true;
  };

  // 待发签约方和签约方拒绝状态
  validateState = () => {
    const { selectedRows } = this.state;
    return selectedRows.some(item => item.billState !== 1 && item.billState !== 3);
  };

  // 发送签约方
  sendContract = () => {
    const { selectedRowKeys } = this.state;
    const { dispatch } = this.props;
    const {
      pageData: { pagination },
      activeKey,
      formFieldsValue,
    } = this.props;
    if (selectedRowKeys.length > 0) {
      if (this.validateState()) {
        message.warning('只有待发签约方和签约方拒绝的可以发送签约方');
        return;
      }
      confirm({
        icon: <QuestionCircleOutlined />,
        title: '你确定要发送吗?',
        okText: '发送',
        okType: 'default',
        cancelText: '取消',
        style: { top: 200 },
        onOk: () => {
          dispatch({
            type: 'chargebillns/sendBillData',
            payload: { billIdList: selectedRowKeys },
          }).then(res => {
            if (res.success) {
              message.success(`${res.message || '发送成功！'}`);
              this.searchList(
                this.processFormData(formFieldsValue),
                activeKey,
                pagination.current,
                pagination.pageSize
              );
            } else {
              message.warning(`${res.message || '发送失败！'}`);
            }
          });
        },
        onCancel: () => {
          this.setState({ selectedRowKeys: [], sumPrice: 0 });
        },
      });
    } else {
      message.warning('请至少选择一条账单数据');
    }
  };

  handleSelectRows = (selectedRows, selectedKeys) => {
    const sum = selectedRows.reduce((total, currentValue) => total + currentValue.billAmo || 0, 0);
    this.setState({ selectedRowKeys: selectedKeys, selectedRows, sumPrice: sum });
  };

  handleStandardTableChange = pagination => {
    const { activeKey, formFieldsValue } = this.props;
    this.searchList(
      this.processFormData(formFieldsValue),
      activeKey,
      pagination.current,
      pagination.pageSize,
      false
    );
  };

  render() {
    const {
      chargebillns,
      form: { getFieldDecorator },
      expandForm,
      activeKey,
      loading,
      formFieldsValue,
      pageData,
      dispatch,
    } = this.props;
    const {
      statusMap,
      sumPrice,
      supplyNameListAll,
      NSBILL_CHRG_STATE,
      selectedRowKeys,
      selectedRows,
      exportLoding,
    } = this.state;
    // 表单布局
    const formItemLayout = {
      labelCol: { md: { span: 7 } },
      wrapperCol: { md: { span: 17 } },
    };
    const columns = [
      {
        title: '账单编号',
        dataIndex: 'billNo',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
      {
        title: '账单年月',
        dataIndex: 'billYm',
        sorter: (a, b) => new Date(b.billYm) - new Date(a.billYm),
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => val && `${val.toString().substr(0, 4)}-${val.toString().substr(4, 5)}`,
      },
      {
        title: '签约方',
        dataIndex: 'sendSuppName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '账单状态',
        dataIndex: 'billState',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: (val, record) => (
          <Badge status={val === 7 ? statusMap[4] : statusMap[val]} text={record.billStateName} />
        ),
      },
      {
        title: '服务类型',
        dataIndex: 'serTypeName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        align: 'center',
      },
      {
        title: '账单金额',
        dataIndex: 'billAmo',
        width: 130,
        onHeaderCell: () => ({ style: { fontWeight: 'bolder', textAlign: 'right' } }),
        onCell: () => ({ style: { textAlign: 'right' } }),
        render: (text, record) => (
          <Tooltip
            placement="top"
            title={
              <div>
                <p>
                  涉及人数：
                  {record.involvePersonNum}
                </p>
                <p>
                  {record.agtsrvIns ? `代收社保：${formatNumber(record.agtsrvIns)}` : ''}
                </p>
                <p>
                  {record.agtsrvAccu ? `代收公积金：${formatNumber(record.agtsrvAccu)}` :''}
                </p>
                <p>
                  {record.agtsrvWage ? `代收工资：${formatNumber(record.agtsrvWage)}` : ''}
                </p>
                <p>
                  {record.othCost ? `服务费：${formatNumber(record.othCost)}` : ''}
                </p>
                <p>
                  {record.bnftAmo ? `福利费：${formatNumber(record.bnftAmo)}` : ''}
                </p>
                <p>
                  {record.medExamAmo ? `体检费：${formatNumber(record.medExamAmo)}` : ''}
                </p>
                <p>
                  {record.cmpinsAmo ? `保险：${formatNumber(record.cmpinsAmo)}` : ''}
                </p>
                <p>
                  {record.riskAmo ? `风险金：${formatNumber(record.riskAmo)}` : ''}
                </p>
              </div>
            }
          >
            {text ? (
              <span>
                {formatNumber(text)}
                <EllipsisOutlined style={{ fontSize: 14, color: '#08c' }} />
              </span>
            ) : (
              <span> {text === 0 ? 0 : '--'}</span>
            )}
          </Tooltip>
        ),
      },
      {
        title: '操作',
        dataIndex: 'remark',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <div>
            <a
              onClick={() =>
                router.push(`/chargmanage/chargebillns/detail?billId=${record.billId}`)
              }
            >
              查看
            </a>
            {(Number(record.billState) === 1 || Number(record.billState) === 3) &&
            record.involvePersonNum > 1 ? (
              <Authorized authority="ns:nsBillChrg:split" noMatch={null}>
                <Divider type="vertical" />
                <a
                  onClick={() =>
                    router.push(`/chargmanage/chargebillns/split?billId=${record.billId}`)
                  }
                >
                  拆分
                </a>
              </Authorized>
            ) : null}
          </div>
        ),
      },
    ];
    // 表格配置 -
    const tableConfig = {
      title: () =>
        chargebillns.isHasTask ? (
          <Alert
            message={
              <span>
                您有正在生成账单的任务
                <a
                  style={{ marginLeft: 20 }}
                  onClick={() => {
                    dispatch({
                      type: 'chargebillns/updateModelData',
                      payload: {
                        showProgress: true,
                      },
                    });
                  }}
                >
                  查看
                </a>
              </span>
            }
            type="warning"
            showIcon
          />
        ) : (
          <Alert
            message={
              <Fragment>
                已选择 <span style={{ color: '#088FEA' }}> {selectedRowKeys.length} </span>项 &nbsp;
                总计： &nbsp;
                <span style={{ fontWeight: 'bold' }}>{sumPrice ? sumPrice.toFixed(2) : 0}</span>
                &nbsp;元
              </Fragment>
            }
            type="info"
            showIcon
          />
        ),
    };
    // 模态框布局
    const formItemLayoutModal = {
      labelCol: { md: { span: 6 } },
      wrapperCol: { md: { span: 16, offset: 1 } },
    };
    // 模态框配置
    const modalConfig = {
      title: '生成账单',
      visible: chargebillns.modalVisible,
      confirmLoading: chargebillns.submitLoading,
      onOk: this.submitData,
      okText: '提交',
      onCancel: () => {
        this.handleModalVisible(false);
      },
      destroyOnClose: true,
    };
    // 字典下拉
    const dictOL = dictList =>
      dictList.map(options => <Option key={options.itemCode}>{options.itemName}</Option>);
    const billingDownload = (
      <Menu>
        {checkPermissions('ns:nsBillChrg:downBillDet') && (
          <Menu.Item onClick={() => this.export('downSingleBillDet')}>单个下载</Menu.Item>
        )}
        {checkPermissions('ns:nsBillChrg:downBill') && (
          <Menu.Item onClick={() => this.export('downMergeBillDet')}>合并下载</Menu.Item>
        )}
      </Menu>
    );
    const moreMenu = (
      <Menu>
        {checkPermissions('ns:nsBillChrg:merge') && (
          <Menu.Item onClick={this.mergeBill}>合并</Menu.Item>
        )}
        {checkPermissions('ns:nsBillChrg:delete') && (
          <Menu.Item onClick={this.deleteBill}>删除</Menu.Item>
        )}
        {checkPermissions('ns:nsBillChrg:updateChrgState') && (
          <Menu.Item onClick={this.markCharge}>标记已收费</Menu.Item>
        )}
      </Menu>
    );
    const renderSimpleForm = (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem {...formItemLayout} label="签约方" style={{ display: 'block' }}>
              {getFieldDecorator('sendSuppId', {
                rules: [{ required: false }],
                initialValue: formFieldsValue.sendSuppId,
              })(<Supplier allowClear />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...formItemLayout} label="账单年月">
              {getFieldDecorator('billYm', {
                initialValue: formFieldsValue.billYm,
              })(<MonthPicker placeholder="请选择" style={{ width: '100%' }} format="YYYY-MM" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" onClick={() => this.searchBtnList(activeKey)}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                重置
              </Button>
              {activeKey === '1' ? (
                <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                  展开 <DownOutlined />
                </a>
              ) : null}
            </span>
          </Col>
        </Row>
      </Form>
    );
    const renderAdvancedForm = (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem {...formItemLayout} label="签约方" style={{ display: 'block' }}>
              {getFieldDecorator('sendSuppId', {
                rules: [{ required: false }],
                initialValue: formFieldsValue.sendSuppId,
              })(<Supplier allowClear />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...formItemLayout} label="账单年月">
              {getFieldDecorator('billYm', {
                initialValue: formFieldsValue.billYm,
              })(<MonthPicker placeholder="请选择" style={{ width: '100%' }} format="YYYY-MM" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...formItemLayout} label="账单状态">
              {getFieldDecorator('billState', {
                initialValue: formFieldsValue.billState,
              })(
                <HOCSelect
                  placeholder="请输入关键字检索"
                  allowClear
                  showSearch
                  optionFilterProp="children"
                >
                  {dictOL(NSBILL_CHRG_STATE)}
                </HOCSelect>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem {...formItemLayout} label="账单编号">
              {getFieldDecorator('billNo', {
                rules: [{ required: false }],
                initialValue: formFieldsValue.billNo,
              })(<Input placeholder="请输入账单编号" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24} />
          <Col md={8} sm={24}>
            <div style={{ overflow: 'hidden' }}>
              <span style={{ float: 'right', marginBottom: 16 }}>
                <Button type="primary" onClick={() => this.searchBtnList(activeKey)}>
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                  重置
                </Button>
                <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                  收起 <UpOutlined />
                </a>
              </span>
            </div>
          </Col>
        </Row>
      </Form>
    );
    const renderForm = expandForm ? renderAdvancedForm : renderSimpleForm;
    return (
      <PageHeaderWrapper>
        <Spin spinning={exportLoding || loading}>
          <Card className={styles.tabCard}>
            <Tabs activeKey={activeKey} onChange={this.changeTabPane}>
              <TabPane tab="账单" key="1">
                {/* <div
                  className={styles.tableListForm}
                  style={{
                    margintop: 4,
                    marginBottom: 16,
                    paddingTop: 16,
                    paddingRight: 16,
                    backgroundColor: '#fafafa',
                  }}
                > */}

                <div
                  className={styles.tableListForm}
                  style={{
                    marginBottom: 16,
                    padding: '24px 24px 0 0',
                    backgroundColor: '#fafafa',
                  }}
                >
                  {renderForm}
                </div>
                <Row>
                  <Authorized authority="ns:nsBillChrg:createBill" noMatch={null}>
                    <Button type="primary" onClick={() => this.handleModalVisible(true)}>
                      生成账单
                    </Button>
                  </Authorized>
                  <Authorized authority="ns:nsBillChrg:sendBillPay" noMatch={null}>
                    <Button
                      type="primary"
                      onClick={() => this.sendContract()}
                      style={{ marginLeft: 8 }}
                    >
                      发送签约方
                    </Button>
                  </Authorized>
                  <Dropdown overlay={billingDownload}>
                    <Button style={{ marginLeft: 8 }}>账单下载</Button>
                  </Dropdown>
                  <Dropdown overlay={moreMenu}>
                    <Button style={{ marginLeft: 8 }}>
                      更多 <DownOutlined />
                    </Button>
                  </Dropdown>
                </Row>
                <StandardTable
                  selectedRows={selectedRows}
                  selectedRowKeys={selectedRowKeys}
                  data={pageData}
                  columns={columns}
                  rowKey="billId"
                  onSelectRow={this.handleSelectRows}
                  onChange={this.handleStandardTableChange}
                  title={tableConfig.title}
                  className={styles.infoStyle}
                />
                {/* 生产账单 */}
                <Modal {...modalConfig}>
                  <Form>
                    <FormItem {...formItemLayoutModal} label="签约方">
                      {getFieldDecorator('suppIdModal', {
                        rules: [{ required: true, message: '请选择' }],
                      })(
                        <HOCSelect
                          placeholder="请输入关键字检索"
                          labelInValue
                          showSearch
                          optionFilterProp="children"
                        >
                          {supplyNameListAll.map(options => (
                            <Option key={options.suppId}>{options.name}</Option>
                          ))}
                        </HOCSelect>
                      )}
                    </FormItem>
                    <FormItem label="截止年月" {...formItemLayoutModal}>
                      {getFieldDecorator('billYmModal', {
                        rules: [{ required: true, message: '请选择' }],
                        initialValue: moment(),
                      })(
                        <MonthPicker
                          placeholder="请选择"
                          disabled
                          // disabledDate={current =>
                          //   current < moment().subtract(1, 'months') ||
                          //   current > moment().add(5, 'months')
                          // }
                          style={{ width: '100%' }}
                        />
                      )}
                    </FormItem>
                  </Form>
                </Modal>
                <TaskProgress
                  progressVisible={chargebillns.showProgress}
                  progressPercent={chargebillns.progressPercent || 0}
                  isShowResult={chargebillns.progressPercent === 100}
                  resultInfo={chargebillns.resultInfo}
                  checkHasTask={this.checkHasTask}
                  handleProgressModalVisible={this.handleProgressModalVisible}
                />
              </TabPane>
              <TabPane tab="未进账单数据" key="2">
                {activeKey === '2' ? <NotEnterBillData value={activeKey} /> : null}
              </TabPane>
            </Tabs>
          </Card>
        </Spin>
      </PageHeaderWrapper>
    );
  }
}

const ListSearchForm = Form.create()(BasicList);
export default ListSearchForm;
